package com.paipai.aop;

import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.UUID;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.paipai.loginInterceptor.LoginInterceptor;
import com.paipai.myannotation.MyLog;
import com.paipai.utils.UserInfo;


import org.aspectj.lang.annotation.Around;

@Aspect
@Component
public class LogAsPect {

	@Autowired
	private RabbitTemplate rabbittemplate;

	@Pointcut("execution( * com.paipai.controller.*.*(..))")
	public void logPointCut() {
	};

	@Around("execution(public * com.paipai.controller.*.*(..))")
	public Object Around(ProceedingJoinPoint p) throws Throwable {
		System.out.println("aop拦截生效");
		
		// 拦截实体类的名字
		String className = p.getTarget().getClass().getSimpleName();
		
		// 拦截方法
		String methodsName = p.getSignature().getName();
		
		// 组合名字
		String fullName = className + ":" + methodsName;

		// 获取方法上的注解,并得到内容
		MethodSignature sig = (MethodSignature) p.getSignature();// 获取类型数组

		Method method = p.getTarget().getClass().getDeclaredMethod(methodsName,sig.getParameterTypes());

		// 判断方法是否有这个注解
		if (method.isAnnotationPresent(MyLog.class)) {
			MyLog annotation = method.getAnnotation(MyLog.class);
			// 获取注解上的value值
			String value = annotation.value();
			UserInfo userInfo = LoginInterceptor.getTlocal();
			
			//用户名
			String username = "";
			if (userInfo == null) {
				username = "未登录用户";
			} else {
				username = userInfo.getUsername();
			}
			
			
			
			//封装成Map对象放进消息队列
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("methods",fullName);//类名+方法名
			map.put("description", value);//注解描述
			map.put("username", username);//执行该操作的用户
			map.put("executionTime", new Date());//执行时间
			
			
			// 消息体
			Message message = MessageBuilder.withBody(JSON.toJSONString(map).getBytes("UTF-8"))
					// 格式
					.setContentType(MessageProperties.CONTENT_TYPE_JSON)
					// 设置编码
					.setContentEncoding("UTF-8")
					// 设置message id
					.setMessageId(UUID.randomUUID().toString()).build();
			
			
			System.out.println("发送消息");
			//放进消息队列
			rabbittemplate.convertAndSend("paipai.log",message);
		}
		return p.proceed();

	}

}
